import { useHttp } from "./http";
import { QueryKey, useMutation, useQuery } from "react-query";
import { cleanObjectPrivate } from "./project";
import { useAddConfig, useDeleteConfig } from "./use-optimistic-options";
import { Task } from "../types/task";
import { Epic } from "../types/epic";

export const useEpics = (param?: Partial<Epic>) => {
  const client = useHttp();
  return useQuery<Epic[]>(["epics", param], () =>
    client("/epics", { data: cleanObjectPrivate(param || {}) })
  );
};

export const useAddEpic = (queryKey: QueryKey) => {
  const client = useHttp();
  return useMutation(
    (params: Partial<Epic>) =>
      client(`/epics`, {
        data: params,
        method: "POST",
      }),
    useAddConfig(queryKey)
  );
};
export const useAddTask = (queryKey: QueryKey) => {
  const client = useHttp();
  return useMutation(
    (params: Partial<Task>) =>
      client(`/tasks`, {
        data: params,
        method: "POST",
      }),
    useAddConfig(queryKey)
  );
};
export const useTask = (id?: number) => {
  const client = useHttp();
  return useQuery<Task>(["task", { id }], () => client(`/tasks/${id}`), {
    enabled: Boolean(id),
  });
};

export const useDeleteEpic = (queryKey: QueryKey) => {
  const client = useHttp();
  return useMutation(({ id }: { id: number }) => {
    console.log("id", id);
    return client(`/epics/${id}`, {
      method: "DELETE",
    });
  }, useDeleteConfig(queryKey));
};
